/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.service.loan;

import com.alibaba.fastjson.JSON;
import com.server.common.persistence.Page;
import com.server.common.security.RSASignUtils;
import com.server.common.security.RSAUtils;
import com.server.common.service.CrudService;
import com.server.common.utils.StringUtils;
import com.server.modules.api.service.IJPushService;
import com.server.modules.api.service.IMService;
import com.server.modules.api.vo.ApplyLoan;
import com.server.modules.sys.common.StaticDefine;
import com.server.modules.sys.dao.loan.CustomPayDao;
import com.server.modules.sys.dao.settlement.SettlementDao;
import com.server.modules.sys.dao.settlement.item.SettlementItemDao;
import com.server.modules.sys.entity.loan.CustomPay;
import com.server.modules.sys.entity.loan.Loan;
import com.server.modules.sys.entity.material.MaterialType;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.entity.settlement.Settlement;
import com.server.modules.sys.entity.settlement.item.SettlementItem;
import com.server.modules.sys.service.member.MemberService;
import com.server.modules.sys.service.settlement.SettlementService;
import com.server.modules.sys.service.settlement.item.SettlementItemService;
import com.server.modules.sys.utils.LogUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 客户申请记录Service
 * @author 王磊
 * @version 2016-09-19
 */
@Service
@Transactional(readOnly = true)
public class CustomPayService extends CrudService<CustomPayDao, CustomPay> {

	@Resource
	private SettlementDao settlementDao;

	@Resource
	private SettlementService settlementService;

	@Resource
	private SettlementItemService settlementItemService;

	@Resource
	private SettlementItemDao settlementItemDao;

	@Autowired
	private IJPushService jPushService;

    @Autowired
    private LoanService loanService;

    @Autowired
    private IMService imService;


    @Autowired
    private MemberService memberService;

	public CustomPay get(String id) {
		return super.get(id);
	}
	
	public List<CustomPay> findList(CustomPay customPay) {
		return super.findList(customPay);
	}
	
	public Page<CustomPay> findPage(Page<CustomPay> page, CustomPay customPay) {
		return super.findPage(page, customPay);
	}
	
	@Transactional(readOnly = false)
	public void save(CustomPay customPay) {
		  super.save(customPay);
	}
	
	@Transactional(readOnly = false)
	public void delete(CustomPay customPay) {
		super.delete(customPay);
	}

	@Transactional(readOnly = false,rollbackFor = { Exception.class }, propagation = Propagation.REQUIRED)
    public boolean payServiceCharge(CustomPay customPay) throws Exception {
		try {
			String orderFlag = customPay.getOrderFlag();
			if(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAY.equals(orderFlag)){
				customPay.setOrderFlag(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WAITTINGCHECK);
				customPay.preUpdate();
				dao.update(customPay);
				String serviceCharge = customPay.getServiceCharge();
				Settlement settlement=new Settlement();
				settlement.setOrders(new Date().getTime() + StringUtils.createOrder(7));
				settlement.setCustomPayId(customPay.getId());
				settlement.setMemberId(customPay.getMemberid());
				settlement.setAmountIn(Long.parseLong(serviceCharge));
				settlement.setRemarks("后台付款");
				settlement.setSettlementDate(new Date());
				settlement.setType(StaticDefine.SETTLEMENT_TYPE.BACK_SC);
				settlement.preInsert();
				settlementDao.insert(settlement);
				SettlementItem item=new SettlementItem();
				item.setRemarks("后台付款");
				item.setPayDate(new Date());
				item.setPayFlag(StaticDefine.SETTLEMENT_ITEM_PAY_FLAG.PAYED);
				item.setSettlementId(settlement.getId());
				item.setType(StaticDefine.SETTLEMENT_ITEM_TYPE.IN);
				item.setSettlementType(StaticDefine.SETTLEMENT_ITEM_SETTLEMENTTYPE.BACK_SC);
				item.setAmount(Long.parseLong(serviceCharge));
				item.preInsert();
                //签名
                item.setSignature(RSASignUtils.sign((item.getAmount()+item.getSettlementId()).getBytes(),RSASignUtils.getKeyByKeyFileName("privateKey.keystore")));
				settlementItemDao.insert(item);
				return true;
			}else{
				return  false;
			}
		}catch (Exception e){
			e.printStackTrace();
			throw e;
		}

    }
	@Transactional(readOnly = false,rollbackFor = { Exception.class }, propagation = Propagation.REQUIRED)
	public boolean checkPassLoan(CustomPay customPay) {
		String orderFlag = customPay.getOrderFlag();
		if(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WAITTINGCHECK.equals(orderFlag)){
			List<ApplyLoan> applyLoanList = dao.findApplyLoanList(customPay);
			customPay.setOrderFlag(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGSETTLEMENT);
			this.save(customPay);
			//还要向用户推送消息
            String loanid = customPay.getLoanid();
            Loan loan = loanService.get(new Loan(loanid));
            if(loan!=null){
                Map<String,Object> msgMap=new HashedMap();
                StringBuilder msg=new StringBuilder();
                msg.append(" 您申请的"+loan.getName()+"已通过审核，请带上");
                //查询出贷款所需资料
                List<MaterialType> lMtys= loanService.getMaterialsByLoanId(loan.getId());
                int i=0;
                for (MaterialType lMty : lMtys) {
                    msg.append(lMty.getName());
                    if(i<lMtys.size()-1){
                        msg.append(",");
                    }
                    i++;
                }
                if(i!=0){
					msg.append("等");
				}
                msg.append("证件");
                msg.append("到公司办理贷款");
                String memberid = customPay.getMemberid();
                List<Member> findList = memberService.findList(new Member(memberid));
                List<String> userList = new ArrayList<>(1);
                for (Member member : findList) {
					if(member.getId().equals(memberid)){
						userList.add(member.getHxUsername());
					}
                }
                ApplyLoan applyLoan=null;
                if(!CollectionUtils.isEmpty(applyLoanList)){
                    applyLoan=applyLoanList.get(0);
                }
                Map<String,String > ext = new HashedMap();
                msgMap.put("type","text");
                ext.put("objId",loan.getId());
                ext.put("type","2");//1为产品，2为申请记录
				ext.put("data", JSON.toJSONString(applyLoan));
                msgMap.put("msg",msg.toString());
                imService.sendSysMessages(userList,msgMap,ext);
            }

		}
		return true;
	}

	@Transactional(readOnly = false,rollbackFor = { Exception.class }, propagation = Propagation.REQUIRED)
    public boolean paySettlement(CustomPay customPay, HttpServletRequest request) throws Exception {
		try {
			String orderFlag = customPay.getOrderFlag();
			if(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAYSETTLEMENT.equals(orderFlag)){
				customPay.setOrderFlag(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.LOANSUCCESS);
				this.save(customPay);
				Settlement settlement=new Settlement();
				settlement.setMemberId(customPay.getMemberid());
				settlement.setType(StaticDefine.SETTLEMENT_TYPE.SETTLEMENT);
				settlement.setCustomPayId(customPay.getId());
				List<Settlement> list = settlementService.findList(settlement);
				Date currentDate = new Date();
				if(!CollectionUtils.isEmpty(list)){
					Settlement settlement1 = list.get(0);
					SettlementItem item=new SettlementItem();
					item.setSettlementId(settlement1.getId());
					List<SettlementItem> items = settlementItemService.findList(item);
					for (SettlementItem settlementItem : items) {
						//校验签名
                        String sign = RSASignUtils.sign((settlementItem.getAmount() + settlementItem.getSettlementId()).getBytes(), RSASignUtils.getKeyByKeyFileName("privateKey.keystore"));
                        if (!RSAUtils.verify((settlementItem.getAmount()+settlementItem.getSettlementId()).getBytes(),RSASignUtils.getKeyByKeyFileName("publicKey.keystore"),settlementItem.getSignature())){
							//数据已被篡改。不需要做更新操作，计入异常日志中，等待进一步数据分析
							LogUtils.saveLog(request,"结算明细数据被篡改id["+settlementItem.getId()+"] 回调不能正常处理，请人工处理");
							throw new Exception("结算明细数据被篡改id["+settlementItem.getId()+"] 回调不能正常处理，请人工处理");
						}
						settlementItem.setPayFlag(StaticDefine.SETTLEMENT_ITEM_PAY_FLAG.PAYED);
						settlementItem.setPayDate(currentDate);
						settlementItem.preUpdate();
						settlementItemDao.update(settlementItem);
						// settlementItemService.save(settlementItem);
					}
					return true;
				}
			}else{
				return  false;
			}
			return false;
		}catch (Exception e){
			e.printStackTrace();
			throw  e;
		}
    }
	@Transactional(readOnly = false,rollbackFor = { Exception.class }, propagation = Propagation.REQUIRED)
    public boolean pushUnPassMsg(CustomPay customPay) {
        String orderFlag = customPay.getOrderFlag();
        if(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WAITTINGCHECK.equals(orderFlag)){
			List<ApplyLoan> applyLoanList = dao.findApplyLoanList(customPay);
            //向用户推送消息
            String loanid = customPay.getLoanid();
            Loan loan = loanService.get(new Loan(loanid));
            if(loan!=null){
                Map<String,Object> msgMap=new HashedMap();
                StringBuilder msg=new StringBuilder();
                msg.append(" 您申请的"+loan.getName()+"未通过审核，该贷款需要");
                //查询出贷款所需资料
                List<MaterialType> lMtys= loanService.getMaterialsByLoanId(loan.getId());
                int i=0;
                for (MaterialType lMty : lMtys) {
                    msg.append(lMty.getName());
                    if(i<lMtys.size()-1){
                        msg.append(",");
                    }
                    i++;
                }
                if(i!=0){
					msg.append("等");
				}
                msg.append("证件，请在app上传所需的全部证件信息");
                String memberid = customPay.getMemberid();
                List<Member> findList = memberService.findList(new Member(memberid));
                List<String> userList = new ArrayList<String>(1);
                for (Member member : findList) {
					if(memberid.equals(member.getId())){
						userList.add(member.getHxUsername());
					}

                }
                Map<String,String > ext = new HashedMap();
                msgMap.put("type","text");
                msgMap.put("msg",msg.toString());
                ext.put("objId",loan.getId());
                ext.put("type","3");//1为产品，2为申请记录
                ApplyLoan applyLoan=null;
                if(!CollectionUtils.isEmpty(applyLoanList)){
                    applyLoan=applyLoanList.get(0);
                }
                ext.put("data",JSON.toJSONString(applyLoan));
                imService.sendSysMessages(userList,msgMap,ext);
            }
        }
        return true;
    }
	@Transactional(readOnly = false,rollbackFor = { Exception.class }, propagation = Propagation.REQUIRED)
	public boolean pushMsgTest() {
		Map<String,String > msg = new HashedMap();
		msg.put("type","text");
		msg.put("msg","你推荐的用户电话号码为:1312366666的用户已成功注册");
		imService.addFriendSingle("eb6850c4648f4120a95ed0130411b8a5","eb6850c4648f4120a95ed0130411b8a5");
		List<String> userList=new ArrayList<>();
		userList.add("eb6850c4648f4120a95ed0130411b8a5");
		imService.sendSysMessages(userList,msg,null);
		return true;
	}

}